import os
import PySide2
import numpy as np
import math,random
from time import time
import pyqtgraph as pg
import matplotlib
import matplotlib.pyplot as plt
from PySide2.QtWidgets import *
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QFile

from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar)

from matplotlib.figure import Figure


dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path

from PySide2.QtWidgets import QApplication, QMessageBox
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QCoreApplication


matplotlib.use("Qt5Agg")  # 声明使用QT5

        #关闭文件

# -*- coding:utf-8 -*-
f = open(r"D:\Code\Python\romantic\words_data.txt","r",encoding="utf-8")
words_list = list(f)
f.close()

length = len(words_list)


def randrand(x):
    num = np.random.uniform()
    num *= x
    num0 = math.floor(num)
    return num0
class MyFigureCanvas(FigureCanvas):
    """
    通过继承FigureCanvas类，使得该类既是一个PyQt5的Qwidget，又是一个matplotlib的FigureCanvas，这是连接pyqt5与matplotlib的关键
    """

    def __init__(self, parent=None, width=10, height=5, xlim=(0, 2500), ylim=(-2, 2), dpi=100):
        # 初始化时将图片的长、宽、像素均初始化给定
        # 其中xlim，ylim 表示横纵坐标的显示范围
        # 创建一个Figure
        self.figure = plt.Figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
        FigureCanvas.__init__(self, self.figure)  # 初始化父类
        self.setParent(parent)

        self.fig1 = self.figure.add_subplot(111)  # 添加子图
        # add_subplot(2,2,4) 添加子图函数，三个参数分别表示纵向分几个子图，横向分几个子图，当前为第几个子图
        self.fig1.spines['top'].set_visible(False)  # 去掉绘图时上面的横线
        self.fig1.spines['right'].set_visible(False)  # 去掉绘图时右面的横线
        self.fig1.set_xlim(xlim)
        self.fig1.set_ylim(ylim)

class Stats():


    def __init__(self):

        self.ui = QUiLoader().load("main.ui")   # 注意是对ui实例化

        self.gv_visual_data_content = MyFigureCanvas(width=self.ui.graphicsView.width()/ 100,
                                            height = self.ui.graphicsView.height() / 100,
                                            )

        self.ui.WordsButton.clicked.connect(self.Romantic)
        self.ui.LoveButton.clicked.connect(self.lovelove)
        self.ui.ExitButton.clicked.connect(QCoreApplication.quit)

    def Romantic(self):
        t0 = time()
        id = randrand(length)
        words = words_list[id]
        QMessageBox.about(self.ui,
                          '每日情话：',
                          str(words))
    def lovelove(self):
        x = np.arange(-1.81, 1.81, 0.02)
        num1 = x ** 2
        num1 = num1 ** (1 / 3)


        y = np.round(num1, 8) + np.round(0.9 * ((3.3 - x * x) ** 0.5) * np.sin(20.1 * math.pi * x), 8)     # 公式
        self.gv_visual_data_content.fig1.clear()  # 由于图片需要反复绘制，所以每次绘制前清空，然后绘图
        self.gv_visual_data_content.fig1.plot(x, y, color ='red')  # 在加在的图形gv_visual_data_content中的子图fig1中画图
        self.graphic_scene = QGraphicsScene()  # 创建一个QGraphicsScene
        # 加载的图形（FigureCanvas）不能直接放到graphicview控件中，必须先放到graphicScene，然后再把graphicscene放到graphicview中
        self.graphic_scene.addWidget(self.gv_visual_data_content)
        # 把图形放到QGraphicsScene中，注意：图形是作为一个QWidget放到放到QGraphicsScene中的
        self.ui.graphicsView.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
        self.ui.graphicsView.show()  # 调用show方法呈现图形






app = QApplication([])
window = Stats()
window.ui.show()
app.exec_()
